package com.example.spring.demo.config;

import com.example.spring.demo.config.properties.MyShardingRuleProperty;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liangchao
 * 11/18/18 9:28 PM
 */
public class MyShardingUtil {

    public static String getDataSourceKey(int index) {
        return "ds_" + index;
    }

    public static String getDataSourceKey(int totalSchema, long id) {
        int dataSource = (int) (id % totalSchema);
        return getDataSourceKey(dataSource);
    }

    public static int getTableNo(int totalTables, long id) {
        return (int) (id % totalTables);
    }
    
    public static String getTableSuffix(MyShardingRuleProperty property, long id) {
        //需要补齐
        int table = (int) (id % property.getTotalTablePerSchema());
        return getSuffix(property, table);
    }

    public static List<String> getTableNames(MyShardingRuleProperty ruleProperty) {
        String tableName = ruleProperty.getTableName();
        List<String> tableNames = new ArrayList<>();
        for (int i = 0; i < ruleProperty.getTotalTablePerSchema(); i++) {
            tableNames.add(tableName + getSuffix(ruleProperty, i));
        }
        return tableNames;
    }

    private static String getSuffix(MyShardingRuleProperty property, int table) {
        if (property.isAlign()) {
            StringBuilder tempSuffix = new StringBuilder(table);
            int length = String.valueOf(table).length();
            while (length <= property.getSuffixLength()) {
                tempSuffix.insert(0, "0");
                length = length + 1;
            }
            return property.getLink() + tempSuffix;
        } else {
            return property.getLink() + table;
        }
    }
}
